import { type ConfigEnv, type UserConfig, defineConfig, loadEnv } from 'vite'
import Vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import eslintPlugin from 'vite-plugin-eslint2'
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { wrapperEnv } from './src/utils/env'
import { dependencies, devDependencies, name, version } from './package.json'
import dayjs from 'dayjs'

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
	const viteEnv = wrapperEnv(loadEnv(mode, process.cwd()))
	console.log('viteEnv:', viteEnv)
	return {
		define: {
			__APP_INFO__: JSON.stringify({
				name,
				version,
				baseURL: viteEnv.VITE_BASE_API,
				mockBaseURL: viteEnv.VITE_MOCK_URL,
				lastBuildTimestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
				pkg: { dependencies, devDependencies, name },
			}),
		},
		server: {
			host: true,
			open: viteEnv.VITE_B_OPEN,
			port: viteEnv.VITE_N_PORT,
			proxy: {
				// apifox
				[viteEnv.VITE_APIFOX_URL]: {
					target: 'https://mock.apifox.cn/m1/4504467-0-default',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/apifox/, ''),
				},
				[viteEnv.VITE_MOCK_URL]: {
					target: ' https://mock.mengxuegu.com/mock/64128ed0fe77f949bc0d7130/v3-management',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/mock-api/, ''),
				},
				'/dev-api': {
					// target: 'https://vue.ruoyi.vip/prod-api',
					target: 'http://127.0.0.1:3000',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/dev-api/, ''),
				},
			},
		},
		resolve: {
			// 配置别名
			alias: {
				'@': resolve(__dirname, 'src'),
			},
		},
		css: {
			preprocessorOptions: {
				// 定义全局 SCSS 变量
				scss: {
					javascriptEnabled: true,
					additionalData: `@use "@/styles/var.scss" as *;`,
				},
			},
		},
		plugins: [
			Vue(),
			UnoCSS(),
			AutoImport({
				/** 自动导入 Vue 相关函数，如：ref, reactive, toRef 等 */
				imports: ['vue', 'vue-router'],
				/** 指定自动导入函数TS类型声明文件路径 (false:关闭自动生成) */
				// dts: 'src/types/auto-imports.d.ts',
				dts: false,
				/**自 动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式) */
				resolvers: [ElementPlusResolver({ importStyle: 'sass' /** 使 ElMessage，ElNotification等 主题样式生效 */ })],
				eslintrc: {
					/** 是否自动生成 eslint 规则，建议生成之后设置 false */
					enabled: false,
				},
				/**是否在 vue 模板中自动导入 */
				vueTemplate: true,
			}),
			Components({
				/** 指定自动导入组件TS类型声明文件路径 (false:关闭自动生成) */
				// dts: 'src/types/components.d.ts',
				dts: false,
				resolvers: [
					/** 自动导入 Element Plus 组件 */
					ElementPlusResolver({
						/** 使自定义 主题样式生效 */
						importStyle: 'sass',
					}),
				],
			}),
			eslintPlugin({
				lintOnStart: false,
				fix: true,
				exclude: ['/dist/', '/.history/'],
			}),
		],
	}
})
